import { ElMessage } from 'element-plus'

export interface TokenInfo {
  token: string | null
  isValid: boolean
  isExpired: boolean
  expiresAt: Date | null
  payload: any
}

export class TokenManager {
  private static readonly TOKEN_KEY = 'token'
  
  // 获取Token信息
  static getTokenInfo(): TokenInfo {
    const token = localStorage.getItem(this.TOKEN_KEY)
    
    if (!token) {
      return {
        token: null,
        isValid: false,
        isExpired: true,
        expiresAt: null,
        payload: null
      }
    }

    try {
      // 解析JWT Token
      const payload = this.parseJWT(token)
      const expiresAt = payload.exp ? new Date(payload.exp * 1000) : null
      const isExpired = expiresAt ? new Date() > expiresAt : false
      
      return {
        token,
        isValid: !isExpired,
        isExpired,
        expiresAt,
        payload
      }
    } catch (error) {
      console.error('Token解析失败:', error)
      return {
        token,
        isValid: false,
        isExpired: true,
        expiresAt: null,
        payload: null
      }
    }
  }

  // 解析JWT Token
  private static parseJWT(token: string): any {
    try {
      const base64Url = token.split('.')[1]
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
      const jsonPayload = decodeURIComponent(
        atob(base64)
          .split('')
          .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
          .join('')
      )
      return JSON.parse(jsonPayload)
    } catch (error) {
      throw new Error('Invalid JWT token format')
    }
  }

  // 检查Token有效性
  static async validateToken(): Promise<boolean> {
    const tokenInfo = this.getTokenInfo()
    
    if (!tokenInfo.token) {
      ElMessage.warning('未找到登录Token，请重新登录')
      return false
    }

    if (tokenInfo.isExpired) {
      ElMessage.error('Token已过期，请重新登录')
      this.removeToken()
      return false
    }

    return true
  }

  // 获取格式化的Token（用于Authorization头）
  static getAuthToken(): string {
    const tokenInfo = this.getTokenInfo()
    
    if (!tokenInfo.isValid) {
      return ''
    }

    // 确保Token以Bearer开头
    const token = tokenInfo.token!
    return token.startsWith('Bearer ') ? token : `Bearer ${token}`
  }

  // 获取原始Token
  static getRawToken(): string {
    const tokenInfo = this.getTokenInfo()
    
    if (!tokenInfo.token) {
      return ''
    }

    // 移除Bearer前缀（如果存在）
    return tokenInfo.token.replace(/^Bearer\s+/i, '')
  }

  // 设置Token
  static setToken(token: string): void {
    // 确保Token格式正确
    const cleanToken = token.replace(/^Bearer\s+/i, '')
    localStorage.setItem(this.TOKEN_KEY, cleanToken)
  }

  // 移除Token
  static removeToken(): void {
    localStorage.removeItem(this.TOKEN_KEY)
  }

  // 刷新Token（如果有刷新逻辑）
  static async refreshToken(): Promise<boolean> {
    try {
      // 这里可以添加Token刷新逻辑
      // 例如调用refresh token API
      console.log('Token刷新功能待实现')
      return false
    } catch (error) {
      console.error('Token刷新失败:', error)
      return false
    }
  }

  // 调试Token信息
  static debugToken(): void {
    const tokenInfo = this.getTokenInfo()
    
    console.group('🔐 Token调试信息')
    console.log('Token存在:', !!tokenInfo.token)
    console.log('Token有效:', tokenInfo.isValid)
    console.log('Token过期:', tokenInfo.isExpired)
    console.log('过期时间:', tokenInfo.expiresAt?.toLocaleString())
    console.log('Token载荷:', tokenInfo.payload)
    
    if (tokenInfo.token) {
      console.log('Token长度:', tokenInfo.token.length)
      console.log('Token前缀:', tokenInfo.token.substring(0, 20) + '...')
    }
    
    console.groupEnd()
  }

  // 检查Token剩余时间
  static getTokenTimeRemaining(): number {
    const tokenInfo = this.getTokenInfo()
    
    if (!tokenInfo.expiresAt) {
      return 0
    }

    const remaining = tokenInfo.expiresAt.getTime() - new Date().getTime()
    return Math.max(0, remaining)
  }

  // 检查Token是否即将过期（5分钟内）
  static isTokenExpiringSoon(): boolean {
    const remaining = this.getTokenTimeRemaining()
    return remaining > 0 && remaining < 5 * 60 * 1000 // 5分钟
  }
}